package com.weme.common.util

import android.animation.ObjectAnimator
import android.content.Context
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.FrameLayout
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.luck.picture.lib.thread.PictureThreadUtils.runOnUiThread
import com.weme.common.R
import com.scwang.smart.refresh.layout.util.SmartUtil.dp2px


@JvmOverloads
fun Context.showToast(text: CharSequence?, duration: Int = Toast.LENGTH_SHORT) {
    text?.let {
        if (TextUtils.isEmpty(it)) {
            return
        }
        runOnUiThread {
            val toast = Toast(UtilsApp.getApp())
            val view = LayoutInflater.from(UtilsApp.getApp()).inflate(R.layout.toast_layout, null, false)
             view.findViewById<TextView?>(R.id.toast_tv).text = it
            view.layoutParams = FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
            )
            toast.duration = duration
            toast.setGravity(Gravity.FILL_HORIZONTAL, 0, dp2px(80f))
            val mObjectAnimator = ObjectAnimator.ofFloat(view, "alpha", 0f, 1f)
            mObjectAnimator.interpolator = AccelerateDecelerateInterpolator()
            mObjectAnimator.duration = 600
            toast.view = view
            if (!mObjectAnimator.isRunning) {
                mObjectAnimator.start()
            }
            toast.show()
        }
    }
}


@JvmOverloads
fun Fragment.showToast(text: CharSequence?, duration: Int = Toast.LENGTH_SHORT) {
    context?.showToast(text, duration)
}

